$(function(){
function getFileExt(path){
    var extArr = path.split(".");
    var ext = extArr[extArr.length-1];
    return ext;
}
$(".uploadComponent").each(function(){
    var comp = $(this);
    var targetUrl = comp.attr("uploadUrl");
    var targetFieldName = comp.attr("uploadField");
    var allowExt = JSON.parse(comp.attr("allow-ext"));
    var fileInput = comp.find("[type=file]");
    var progress = comp.find("progress")[0];
    var messageDiv = comp.find('.upload-message');
    fileInput.on("change",function(){
        messageDiv.text("");
        var file = this.files[0];
        var ext = getFileExt(file.name);
        if ($.inArray(ext,allowExt)==-1){
            messageDiv.text('不允许的扩展名 '+ext);
            return;
        }
        var data = new FormData();
        data.append(targetFieldName,file);
        $.ajax({
            url: targetUrl,
            type: "POST",
            data: data,
            cache: false,
            contentType: false,
            processData: false,
            dataType: "json",
            success: function(data) {
                if (data.err!==""){
                    messageDiv.text(data.err);
                    return;
                }
                comp.find('.upload-set-input').val(data.data);
            },
            error: function (error) {
                messageDiv.text(data.err);
            },
            xhr: function () {
                _xhr = $.ajaxSettings.xhr();
                if ( _xhr.upload ) {
                    _xhr.upload.onprogress = function (event) {
                        if ( event.lengthComputable ) {
                            progress.value = ( event.loaded / event.total || 0 );
                        }
                    }
                }
                return _xhr;
            }
        });
    });
});
});
